<?php
/**
* phpDjango request handler
* @use httpRequestBean
*/
class Django_requestHandler extends wakService {

	/**
	* @var array config data
	*/
	protected $cfg=array(
		'urlsconf'=>'cfg/django/urlsconf.yml'
	);

	/**
	* called by __construct
	* loads configuration data
	* @access protected
	*/
	protected function _init() {
		// reads routing configuration
		$this->routes=spyc::YamlLoad($this->cfg['urlsconf']);
		if (!$this->routes) {
			throw new Exception("there is no url routing data");
		}
	}/**/
	
	/**
	* serves http request
	* @access public
	* @param httpRequestBean
	* @return httpResponse
	*/
	public function serveRequest($request=null) {
		// get current request if not provided
		if (!is_a($request,'django_httprequest')) {
			$request=django_httpRequest::getCurrent();
		}
		//print_r($request);
		// search for appropriate view
		foreach ($this->routes as $urldata) {
			$urlconf = new django_urlconf($urldata);
			//print_r($urlconf);
			//echo $urlconf;
			if ($urlconf->matchRequest($request)) {
				$view=$urlconf->view;
				$response=$this->_runView($view,$request);
				$this->_sendResponse($response);
			}
		}
		// no match, raise a 404
		$response=new django_httpResponse404();
		$this->_sendResponse($response);
	}/**/
	/**
	* alias for serveRequest
	*/
	function run($request=null) {
		return $this->serveRequest();
	}/**/

	/**
	* runs a view for http request
	* @access private
	* @param string $view class.method
	* @param django_httprequest
	* @return django_httpresponse
	*/
	private function _runView($view,&$request) {
		$s=$this->pkg->getService('views');
		$r=$s->runView($view,$request);
		if (!is_a($r,'django_httpresponse')) {
			throw new Exception("view must return a django_httpresponse");
		}
		return $r;
	}/**/
	
	private function _sendResponse(&$response) {
		$response->send();
		exit;
	}

}

?>
